package com.jarchie.seemovies.mvp.presenter;


import com.jarchie.seemovies.mvp.Api;
import com.jarchie.seemovies.mvp.contact.MovieContact;
import com.jarchie.seemovies.mvp.model.MovieBean;
import com.seemovies.sdk.mvp.impl.BasePresenterImpl;
import com.seemovies.sdk.retrofit.ExceptionHelper;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Jarchie on 2017\11\7.
 * 描述：首页列表数据的处理类
 */

public class MoviePresenter extends BasePresenterImpl<MovieContact.view>
        implements MovieContact.presenter {

    public MoviePresenter(MovieContact.view view) {
        super(view);
    }

    @Override
    public void getData(int pageNum, int pageSize) {
        Api.getInstance().indexList(pageNum, pageSize)
                .subscribeOn(Schedulers.io()) //io线程取数据
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        addDisposable(disposable);
                        view.showLoading();
                    }
                })
                .map(new Function<MovieBean, List<MovieBean.DataBean.MoviesBean>>() {
                    @Override
                    public List<MovieBean.DataBean.MoviesBean> apply(@NonNull MovieBean indexListBean) throws Exception {
                        return indexListBean.getData().getMovies();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread()) //转发到主线程进行展示
                .subscribe(new Consumer<List<MovieBean.DataBean.MoviesBean>>() {
                    @Override
                    public void accept(@NonNull List<MovieBean.DataBean.MoviesBean> dataBeen) throws Exception {
                        view.dismissLoading();
                        view.setData(dataBeen);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        view.dismissLoading();
                        ExceptionHelper.handleException(throwable);
                    }
                });
    }
}
